package com.example.sicnuaccountingapp.ui.auth

import androidx.lifecycle.viewModelScope
import com.example.sicnuaccountingapp.base.BaseViewModel
import com.example.sicnuaccountingapp.data.repository.UserRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AuthViewModel @Inject constructor(
    private val userRepository: UserRepository
) : BaseViewModel<AuthUiState>() {

    private val _authState = MutableStateFlow<AuthUiState>(AuthUiState.Initial)
    val authState: StateFlow<AuthUiState> = _authState.asStateFlow()

    fun login(username: String, password: String) {
        viewModelScope.launch {
            try {
                _authState.value = AuthUiState.Loading
                val user = userRepository.loginUser(username, password)
                if (user != null) {
                    _authState.value = AuthUiState.Success(user.userId)
                } else {
                    _authState.value = AuthUiState.Error("登录失败，请检查用户名和密码")
                }
            } catch (e: Exception) {
                _authState.value = AuthUiState.Error(e.message ?: "登录失败")
            }
        }
    }

    fun register(username: String, password: String, email: String?, phone: String?) {
        viewModelScope.launch {
            try {
                _authState.value = AuthUiState.Loading
                val userId = userRepository.registerUser(username, password, email, phone)
                _authState.value = AuthUiState.Success(userId)
            } catch (e: Exception) {
                _authState.value = AuthUiState.Error(e.message ?: "注册失败")
            }
        }
    }
} 